#include "iso_tp_cfg.h"
// #include "iso_tpif.h"
#include "isotp.h"

#define ISOTP_BUFSIZE 128
static IsoTpLink g_link;
static uint8_t g_isotpRecvBuf[ISOTP_BUFSIZE];
static uint8_t g_isotpSendBuf[ISOTP_BUFSIZE];

uint8_t payload[128] = {0};
uint16_t payload_size = 128;

uint8_t iso_tp_init()
{
    isotp_init_link(&g_link, 0x711,
                    g_isotpSendBuf, sizeof(g_isotpSendBuf),
                    g_isotpRecvBuf, sizeof(g_isotpRecvBuf));

    return 0;
}

void iso_tp_server()
{
    uint32_t recv_id = 0; // 接收到数据的ID
    uint16_t out_size = 0;
    uint8_t recv_len = 0;
    int ret = 0;
    uint8_t rxdata[8] = {0}; // canif层抛上来的接收数据

    recv_len = CAN1_Recv_Msg(&recv_id, rxdata);
    if (recv_len > 0)
    {
        if (recv_id == 0x0D2) // 收到接收ID
        {
            isotp_on_can_message(&g_link, rxdata, recv_len); // 讲数据传递给tp层
        }
    }
    isotp_poll(&g_link); // tp层服务server

    ret = isotp_receive(&g_link, payload, payload_size, &out_size);
    if (ISOTP_RET_OK == ret)
    {
        /* Handle received message */
        printf("isotp_receive: \r\n");
        for (uint8_t i = 0; i < out_size; i++)
        {
            printf("%02X ", payload[i]);
        }
        printf("\r\n");

        /* And send message with isotp_send */
        ret = isotp_send(&g_link, payload, payload_size);
        if (ISOTP_RET_OK == ret)
        {
            /* Send ok */
            printf("isotp_send\r\n");
        }
        else
        {
            printf("send recv error\r\n");
        }
    }
}


void iso_tp_send_test()
{
       uint8_t txdata[128] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                        0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 
                        0x18, 0x19, 0x20};
       for(uint8_t i = 0; i<128; i++)
                        {
                        
                        txdata[i] = i;
                        
                        }
                            
                            
                            
      int  ret = isotp_send(&g_link, txdata, sizeof(txdata));
        if (ISOTP_RET_OK == ret)
        {
            /* Send ok */
            printf("isotp_send\r\n");
        }
        else
        {
            printf("send recv error\r\n");
        }
}
    
    
//https://blog.csdn.net/kian9one/article/details/140085589#:~:text=CAN%20Transp
//单帧测试:
    // 04 11 22 33 44 55 55 55  

//多帧测试： 2E F1 90 01 02 03 01 02 03 04 05 06 07 08 09 10 11 12 13 14
    // 首帧：(LEN:20)
    // 10 14 2E F1 90 01 02 03

    // 连续帧:(20+1)
    // 21 01 02 03 04 05 06 07
    // 连续帧:(20+2)
    // 22 08 09 10 11 12 13 14  



    //最长数据7x15 + 6 = 111